//
//  LGMedicineBallDetailController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/25.
//

#import "LGMedicineBallDetailController.h"
//手术报告
#import "LGOutRecordDetailController.h"
//电话随访
#import "LGMedicineBallPhoneController.h"
//调整计划
#import "LGPatientCarePlanAddController.h"
//上传报告
#import "LGUploadReportPhotoController.h"
//更新入院进展
#import "LGMedicineBallPlanController.h"
//修改随访记录
#import "LGMedicineBallFollowUpRecorder.h"
//患者详情
#import "LGPatientDetailController_YHJK.h"
#import "LGPatientDetailController2.h"
//忽略理由
#import "LGFollowOmitReasonView.h"
#import "LGPatientNavigationView.h"
#import "LGMedicineBallDetailHeader.h"
#import "LGBallDetailOperationCell.h" //手术
#import "LGBallDetailOperatPlanCell.h" //入院计划
#import "LGBallDetailFollowNormalCell.h" //随访--normal
#import "LGBallDetailFollowRecordCell.h" //随访--随访总结
#import "MCPlayer.h"
@interface LGMedicineBallDetailController ()<UITableViewDelegate,UITableViewDataSource,LGBallDetailFollowRecordDelegate>
/**   */
@property (nonatomic , strong)LGPatientNavigationView *navView;
/**   */
@property (nonatomic , strong)LGMedicineBallDetailHeader *headView;
/**   */
@property (nonatomic , strong)CAGradientLayer *shadowLayer;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**  忽略 */
@property (nonatomic , strong)UIButton *omitButton;
/**  调整计划 */
@property (nonatomic , strong)UIButton *adjustButton;
/**  上传报告 */
@property (nonatomic , strong)UIButton *uploadButton;
/**   */
@property (nonatomic , strong)UIView *shadowView;
/**   */
@property (nonatomic , strong)NSArray *operationArray;
/**   */
@property (nonatomic , strong)NSDictionary *planDic;
/**   */
@property (nonatomic , strong)NSArray *followArray;
/**   */
@property (nonatomic , strong)NSArray *reportArray;
/**   */
@property (nonatomic , copy)NSString *taskid;
@end

@implementation LGMedicineBallDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createSubView];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[MCPlayer shareManager] stopMedia];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/Careplan/taskDetail" parameters:@{@"id":self.planid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.planDic = returnData;
            self.taskid = LGNSString(returnData[@"id"]);
            self.navView.patientDic = returnData[@"patient"];
            self.headView.dataDic = returnData[@"patient"];
            self.operationArray = returnData[@"patient"][@"surgery"];
            self.reportArray = returnData[@"report_imgs"];
            self.operatName = LGNSString(returnData[@"task_type_name"]);
            [self.tableView reloadData];
            NSString *mobile = LGNSString(returnData[@"patient"][@"mobile"]);
            CGFloat height = (mobile.length>0)?viewPix(115):viewPix(72);
            self.headView.frame = CGRectMake(0, 0, Screen_W, height);
            self.tableView.tableHeaderView = self.headView;
            
            //-1|未上传已过期 0|未上传 1|已上传 2|已忽略
            CGFloat buttonW = (Screen_W-viewPix(44))/3.0;
            NSString *status = LGNSString(returnData[@"reportup_status"]);
            if ([status isEqualToString:@"1"] || [status isEqualToString:@"2"]) {
                //已忽略、已上传 -- 不显示”忽略“按钮
                self.omitButton.hidden = YES;
                buttonW = (Screen_W-viewPix(32))/2.0;
                self.adjustButton.frame = CGRectMake(viewPix(10), viewPix(12), buttonW, viewPix(46));
                self.uploadButton.frame = CGRectMake(kMaxX(self.adjustButton.frame)+viewPix(12), viewPix(12), buttonW, viewPix(46));
            }else{
                self.omitButton.hidden = NO;
                self.adjustButton.frame = CGRectMake(kMaxX(self.omitButton.frame)+viewPix(12), viewPix(12), buttonW, viewPix(46));
                self.uploadButton.frame = CGRectMake(kMaxX(self.adjustButton.frame)+viewPix(12), viewPix(12), buttonW, viewPix(46));
            }
            
        }else if (code == 403){
            if(self.refreshTableData){
                self.refreshTableData();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } error:^(NSError *error) {
    }];
    
    [RequestUtil withPOST:@"/doctor/patient.followup_advice/search" parameters:@{@"patient_id":self.patientid,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.followArray = returnData;
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
    
}

//跳转患者详情
-(void)checkPatientDetailAction{
    NSDictionary *tempDic = self.planDic[@"patient"];
    NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
    if ([nodePage isEqualToString:@"1"]) {
        //市一慢阻肺
        LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
        controller.patientid = LGNSString(tempDic[@"patient_id"]);
        controller.levelid = LGNSString(tempDic[@"level_id"]);
        controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        //其他
        LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
        controller.patientid = LGNSString(tempDic[@"patient_id"]);
        controller.levelid = LGNSString(tempDic[@"level_id"]);
        controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
        [self.navigationController pushViewController:controller animated:YES];
    }
}

//电话随访
-(void)makePhoneFollowUpAction{
    LGMedicineBallPhoneController *controller = [[LGMedicineBallPhoneController alloc]init];
    controller.patientid = self.patientid;
    controller.planid = @"0";
    controller.levelid = self.levelid;
    controller.type = @"plan";
    [self.navigationController pushViewController:controller animated:YES];
}

//修改随访记录
-(void)reviseFollowUpRecord:(NSString *)followid{
    LGMedicineBallFollowUpRecorder *controller = [[LGMedicineBallFollowUpRecorder alloc]init];
    controller.followid = followid;
    [self.navigationController pushViewController:controller animated:YES];
}

//调整计划
-(void)adjustPlanAction{
    LGPatientCarePlanAddController *controller = [[LGPatientCarePlanAddController alloc]init];
    controller.taskid = self.taskid;
    controller.patientid = self.patientid;
    controller.levelid = self.levelid;
    [self.navigationController pushViewController:controller animated:YES];
}

//忽略
-(void)omitPlanAction{
    LGFollowOmitReasonView *reasonView = [[LGFollowOmitReasonView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    [LGKeyWindow addSubview:reasonView];
    __weak typeof(self) weakSelf = self;
    reasonView.omitReasonAction = ^(NSString * _Nonnull reason) {
        [RequestUtil withPOST:@"/doctor/Careplan/upReportOmit" parameters:@{@"id":weakSelf.planid , @"omit_reason":reason} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [weakSelf requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"保存失败，请重试" offset:0];
        }];
    };
}

//上传报告
-(void)uploadReportAction{
    LGUploadReportPhotoController *controller = [[LGUploadReportPhotoController alloc]init];
    controller.photoArray = self.reportArray;
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.uploadPhotoReportSuccess = ^(NSArray * _Nonnull photoArray) {
        [RequestUtil withPOST:@"/doctor/Careplan/upReport" parameters:@{@"id":weakSelf.taskid , @"images":photoArray} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [self requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"报告上传失败，请重新上传" offset:0];
        }];
    };
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return self.operationArray.count;
    }else if (section == 1){
        return 1;
    }else{
        return self.followArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        //手术记录
        LGBallDetailOperationCell *operatCell = [tableView dequeueReusableCellWithIdentifier:@"operationCell" forIndexPath:indexPath];
        operatCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *tempDic = self.operationArray[indexPath.row];
        operatCell.content = [NSString stringWithFormat:@"%@   %@",tempDic[@"date"],tempDic[@"short_names"]];
        return operatCell;
        
    }else if(indexPath.section == 1){
        //计划入院
        LGBallDetailOperatPlanCell *planCell = [tableView dequeueReusableCellWithIdentifier:@"planCell" forIndexPath:indexPath];
        planCell.selectionStyle = UITableViewCellSelectionStyleNone;
        planCell.dataDic = self.planDic;
        return planCell;
        
    }else if(indexPath.section == 2){
        NSString *indexType;
        if(indexPath.row == 0){
            indexType = (self.followArray.count == 1) ? @"single" : @"top";
        }else if (indexPath.row == self.followArray.count-1){
            indexType = @"bottom";
        }else{
            indexType = @"middle";
        }
        NSDictionary *tempDic = self.followArray[indexPath.row];
        //1-电话随访 、 2-短信随访 、 3-随访总结 、 4-计划调整
        NSString *type = LGNSString(tempDic[@"followup_type"]);
        if([type isEqualToString:@"3"]){
            //随访记录 -- 随访总结
            LGBallDetailFollowRecordCell *recordCell = [tableView dequeueReusableCellWithIdentifier:@"recordCell" forIndexPath:indexPath];
            recordCell.selectionStyle = UITableViewCellSelectionStyleNone;
            recordCell.dataDic = tempDic;
            recordCell.type = indexType;
            recordCell.delegate = self;
            return recordCell;

        }else{
            //随访记录 -- noramal
            LGBallDetailFollowNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:@"normalCell" forIndexPath:indexPath];
            normalCell.selectionStyle = UITableViewCellSelectionStyleNone;
            normalCell.dataDic = tempDic;
            normalCell.type = indexType;
            return normalCell;
        }
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        NSDictionary *tempDic = self.operationArray[indexPath.row];
        LGOutRecordDetailController *controller = [[LGOutRecordDetailController alloc]init];
        controller.recordid = @"";
        controller.patientid = self.patientid;
        controller.reportDate = LGNSString(tempDic[@"surgery_date"]);
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return 0.01;
    }else{
        return viewPix(46);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = (section == 0)?0.01:viewPix(46);
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    baseView.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
    
    if(section > 0){
        UIView *iconView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(16), 4, viewPix(14))];
        iconView.backgroundColor = [UIColor colorWithString:@"#77D4C6"];
        iconView.cornerRidus = 2;
        [baseView addSubview:iconView];
        
        NSString *title = (section == 1)?self.operatName:@"随访记录";
        UILabel *titleLabel = [UILabel lableWithText:title colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(32), viewPix(12), viewPix(150), viewPix(22));
        [baseView addSubview:titleLabel];
    }
    
    return baseView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 0){
        return viewPix(8);
    }else if (section == 2 && self.followArray.count == 0){
        return viewPix(350);
    }else{
        return 0.01;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 2 && self.followArray.count == 0){
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(350))];
        footView.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
        LGEmptyView *emptyView = [[LGEmptyView alloc]initWithFrame:CGRectMake(viewPix(16), 0, Screen_W-viewPix(32), viewPix(330))];
        emptyView.backgroundColor = [UIColor whiteColor];
        emptyView.userInteractionEnabled = NO;
        emptyView.cornerRidus = 15;
        [emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:viewPix(50)];
        [footView addSubview:emptyView];
        return footView;
    }else{
        CGFloat height = (section == 0)?viewPix(8):0.01;
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
        footView.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
        return footView;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView == self.tableView){
        CGFloat height = scrollView.contentOffset.y;
        if(height<0){
            self.shadowView.frame = CGRectMake(0, topBarHeight, Screen_W, 1-height);
        }else{
            self.shadowView.frame = CGRectMake(0, topBarHeight, Screen_W, 0);
        }
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
    [self.view addSubview:self.shadowView];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.tableView];
    [self createBottomView];
}

-(LGPatientNavigationView *)navView{
    if(!_navView){
        _navView = [[LGPatientNavigationView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight)];
        _navView.backgroundColor = [UIColor colorWithString:@"#E5F3FF"];
        [_navView.backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_navView.checkButton addTarget:self action:@selector(checkPatientDetailAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _navView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(80)-bottomSafeBarHeight/5.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGBallDetailOperationCell class] forCellReuseIdentifier:@"operationCell"];
        [_tableView registerClass:[LGBallDetailOperatPlanCell class] forCellReuseIdentifier:@"planCell"];
        [_tableView registerClass:[LGBallDetailFollowNormalCell class] forCellReuseIdentifier:@"normalCell"];
        [_tableView registerClass:[LGBallDetailFollowRecordCell class] forCellReuseIdentifier:@"recordCell"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headView;
//        [_tableView.layer addSublayer:self.shadowLayer];
    }
    return _tableView;
}

-(UIView *)shadowView{
    if(!_shadowView){
        _shadowView = [[UIView alloc]initWithFrame:CGRectMake(0, topBarHeight, Screen_W, viewPix(115))];
        _shadowView.backgroundColor = [UIColor colorWithString:@"#E5F3FF"];
    }
    return _shadowView;
}

-(LGMedicineBallDetailHeader *)headView{
    if(!_headView){
        _headView = [[LGMedicineBallDetailHeader alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(115))];
        _headView.backgroundColor = [UIColor colorWithString:@"#E5F3FF"];
        [_headView.phoneButton addTarget:self action:@selector(makePhoneFollowUpAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headView;
}

-(CAGradientLayer *)shadowLayer{
    if(!_shadowLayer){
        _shadowLayer = [CAGradientLayer layer];
        _shadowLayer.frame = CGRectMake(0,0,Screen_W,topBarHeight+viewPix(115));
        _shadowLayer.startPoint = CGPointMake(0.5, 0);
        _shadowLayer.endPoint = CGPointMake(0.5, 1);
        _shadowLayer.colors = @[(__bridge id)[UIColor colorWithString:@"#E5F3FF"].CGColor, (__bridge id)[UIColor colorWithString:@"#F3F9FE"].CGColor, (__bridge id)[UIColor colorWithString:@"#FEFEFF"].CGColor];
        _shadowLayer.locations = @[@(0), @(0.4f), @(1.0f)];
    }
    return _shadowLayer;
}

-(void)createBottomView{
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, Screen_H-kMaxY(self.tableView.frame))];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    
    CGFloat buttonW = (Screen_W-viewPix(44))/3.0;
    
    UIButton *omitButton = [UIButton buttonWithTitle:@"忽略" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#429BFF" selectColor:@"#429BFF"];
    omitButton.frame = CGRectMake(viewPix(10), viewPix(12), buttonW, viewPix(46));
    omitButton.layer.borderColor = [UIColor colorWithString:@"#429BFF"].CGColor;
    omitButton.layer.borderWidth = 1;
    omitButton.cornerRidus = 10;
    [omitButton addTarget:self action:@selector(omitPlanAction) forControlEvents:UIControlEventTouchUpInside];
    self.omitButton = omitButton;
    [bottomView addSubview:omitButton];
    
    UIButton *adjustBtn = [UIButton buttonWithTitle:@"调整计划" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#429BFF" selectColor:@"#429BFF"];
    adjustBtn.frame = CGRectMake(kMaxX(omitButton.frame)+viewPix(12), viewPix(12), buttonW, viewPix(46));
    adjustBtn.layer.borderColor = [UIColor colorWithString:@"#429BFF"].CGColor;
    adjustBtn.layer.borderWidth = 1;
    adjustBtn.cornerRidus = 10;
    [adjustBtn addTarget:self action:@selector(adjustPlanAction) forControlEvents:UIControlEventTouchUpInside];
    self.adjustButton = adjustBtn;
    [bottomView addSubview:adjustBtn];
    
    UIButton *uploadBtn = [UIButton buttonWithTitle:@"上传报告" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
    uploadBtn.frame = CGRectMake(kMaxX(adjustBtn.frame)+viewPix(12), viewPix(12), buttonW, viewPix(46));
    uploadBtn.backgroundColor = [UIColor colorWithString:@"#429BFF"];
    uploadBtn.cornerRidus = 10;
    [uploadBtn addTarget:self action:@selector(uploadReportAction) forControlEvents:UIControlEventTouchUpInside];
    self.uploadButton = uploadBtn;
    [bottomView addSubview:uploadBtn];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
